<template>
  <div class="callback-container">
    <div class="callback-content">
      <div class="spinner"></div>
      <h2>正在处理钉钉登录...</h2>
      <p>{{ message }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const message = ref('请稍候，我们正在验证您的身份...')

onMounted(async () => {
  try {
    // 获取URL参数中的code
    const code = route.query.code
    const state = route.query.state
    
    if (!code) {
      message.value = '登录参数错误，请重新登录'
      setTimeout(() => {
        router.push('/login')
      }, 3000)
      return
    }
    
    // 发送到后端处理钉钉登录
    const response = await axios.post('/api/auth/dingtalk-callback', {
      code: code,
      state: state
    })
    
    if (response.data.success) {
      // 存储Token
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('user', JSON.stringify(response.data.user))
      
      message.value = '登录成功，正在跳转...'
      
      // 跳转到主页或来源页面
      setTimeout(() => {
        router.push('/home')
      }, 1000)
    } else {
      throw new Error(response.data.message || '登录失败')
    }
  } catch (error) {
    console.error('钉钉登录失败:', error)
    message.value = error.response?.data?.message || '登录失败，请重新登录'
    
    // 3秒后跳转回登录页
    setTimeout(() => {
      router.push('/login')
    }, 3000)
  }
})
</script>

<style scoped>
.callback-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1a1a1a;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

.callback-content {
  text-align: center;
  padding: 40px;
  background: #2a2a2a;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 36, 66, 0.3);
  border-top: 4px solid #ff2442;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

h2 {
  font-size: 24px;
  margin-bottom: 16px;
  color: #fff;
}

p {
  font-size: 16px;
  color: #999;
  margin: 0;
}
</style>